<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Link;
use App\Permission;
use App\Solve;
use App\Task;
use App\User;
use App\Utils;
use Auth;
use DB;
use Illuminate\Http\Request;
use Input;
use Log;
use Redirect;
use Session;
use Validator;
use View;

class projectsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
    ;    */

    static $URL = '/';

    public function __construct()
    {
        //$this->middleware('auth');
    }

    public function help(Request $request)
    {
        Utils::log($request, 'help');
        $type = "help";
        $input = $request->all();
        if (isset($input['tag']))
            $tag = $input['tag'];
        else $tag = "";
        return View("projects.help", compact('type'), compact('tag'));
    }

    public function newhome(Request $request, $id = null)
    {
        if (!isset($_COOKIE['uuid'])) {
            $uuid = uniqid();
            setcookie("uuid", $uuid);
        }
        if (!Auth::check()) {
            return Redirect::to("/explore");
        }

        Utils::log($request, 'home');
        if (Auth::check()) {
            Auth::user()->last_login_time = time();
            Auth::user()->save();
        }
        $tasks = Task::all();
        $links = Link::all();

        if ($id == null) {
            $user = Auth::user();
            $data = Solve::whereUseridAndType($user->id, 0)
                ->get();
        } else {
            $id = Utils::url2id($id);
            $user = User::findOrFail($id);
            $data = Solve::whereUseridAndType($user->id, 0)
                ->get();
        }
        $solve = array();
        foreach ($tasks as $task) {
            $solve[$task->id] = 0;
        }
        foreach ($data as $d) {
            $solve[$d->taskid] = 1;
        }
        foreach ($links as $link) {
            if ($solve[$link->second] == 1) continue;
            if ($solve[$link->first] == 1) {
                $solve[$link->second] = 2;
            }
        }
        if ($solve[1] == 0) $solve[1] = 2;
        if (count($data) > 50) {
            if ($solve[36] == 0) $solve[36] = 2;
            if ($solve[69] == 0) $solve[69] = 2;
        }

        $medal = DB::select('select class,title from medals where userid=' . $user->id);
        $type = 'tree';

        return View::make('projects.newhome1')->with(compact('solve'))->with(compact('tasks'))->with(compact('links'))->with(compact('user'))->with(compact('type'))->with(compact('medal'));
    }

    public function edittree(Request $request, $id = null)
    {
        if (!Permission::user_is_super()) {
            return view('errors.404');
        }
        if (!isset($_COOKIE['uuid'])) {
            $uuid = uniqid();
            setcookie("uuid", $uuid);
        }
        if (!Auth::check()) {
            return Redirect::to("/explore");
        }

        Utils::log($request, 'home');
        if (Auth::check()) {
            Auth::user()->last_login_time = time();
            Auth::user()->save();
        }
        $tasks = Task::all();
        $links = Link::all();

        if ($id == null) {
            $user = Auth::user();
        } else {
            $id = Utils::url2id($id);
            $user = User::findOrFail($id);
        }
        $solve = array();
        foreach ($tasks as $task) {
            $solve[$task->id] = 1;
        }
        foreach ($links as $link) {
            if ($solve[$link->second] == 1) continue;
            if ($solve[$link->first] == 1) {
                $solve[$link->second] = 2;
            }
        }
        if ($solve[1] == 0) $solve[1] = 2;

        $medal = DB::select('select class,title from medals where userid=' . $user->id);
        $type = 'tree';

        return View::make('projects.edittree')->with(compact('solve'))->with(compact('tasks'))->with(compact('links'))->with(compact('user'))->with(compact('type'))->with(compact('medal'));
    }
    
///////////////////
    public function imagehome(){
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }

        $destinationPath = self::getrootdir();
        $imgs = array();
        $t_paths = array();
        foreach (scandir($destinationPath) as $afile) {
            if ($afile == '.' || $afile == '..') continue;
            $path = self::$URL . $destinationPath . '/' . $afile;
            $t = filemtime($destinationPath . '/' .$afile);
            $t_paths[$t] = $path;
        }
        krsort($t_paths);
        foreach($t_paths as $path){
            $imgs[]['path'] = $path;
        }


        $username = Auth::user()->name;
        return View::make('projects.imagehome')->with(compact('imgs'))->with(compact('username'));
    }

    public function upload()
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
		$res=array();
        $file = array('image' => Input::file('image'));
        $rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
        // doing the validation, passing post data, rules and the messages
        $validator = Validator::make($file, $rules);
        if ($validator->fails()) {
            // send back to the page with the input data and errors
            return Redirect::to('upload')->withInput()->withErrors($validator);
        }
        // checking file is valid.
        if (Input::file('image')->isValid()) {
            $destinationPath = self::getrootdir(); // upload path
            $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
			if($extension=="php")
			{
				return;
			}
            $fileName = time() . rand(11111, 99999) . '.' . $extension; // renameing image
            Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
            // sending back with message
            Session::flash('success', '上传成功   ' . self::$URL . $destinationPath . '/' . $fileName);
			$res['path'] = "http://www.qlcoder.com/".self::$URL . $destinationPath . '/' . $fileName;
			$res['suc']=true;
			return response()->json($res);
        } else {
            // sending back with error message.
			$res['path']="uploaded file is not valid";
			$res['suc']=true;
			return response()->json($res);
        }
    }

    public static function getrootdir()
    {
        $email = Auth::user()->email;
        $emailpath = substr(md5($email), 0, 10);
        $destinationPath = 'uploads/' . $emailpath; // upload path
        if (!is_dir($destinationPath)) mkdir($destinationPath);
        return $destinationPath;
    }

    public function showimage(Request $request)
    {
        $destinationPath = self::getrootdir();
        $cnt = 0;
        $imgs = array();
        foreach (scandir($destinationPath) as $afile) {
            if ($afile == '.' || $afile == '..') continue;
            $path = self::$URL . $destinationPath . '/' . $afile;
            $imgs[] = $path;
        }
        return View::make('projects.show')->
        with(compact('imgs'));
    }

    public function deleteimage(Request $request)
    {
		$res=array();
        $deletepath = $request->all()['deletepath'];
        $arr = explode("/", $deletepath);
        $deletefile = $arr[count($arr) - 1];
        $path = self::getrootdir() . "/" . $deletefile;

        if (file_exists($path)) {
            if (!unlink($path)) {
				$res['res']=true;
				return response()->json($res);
            } else {
				$res['res']=false;
				return response()->json($res);
            }
        } else {

		$res['res']=false;
			return response()->json($res);
        }
    }


///////////////////////////////////////////////////
    public function admin2(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('train.admin1');
        }

        $input = $request->all();
        $uname = $input['username'];
        $password = $input['password'];
        if ($uname != "shinian") echo "账号不存在";
        else echo "密码错误";
        $a = rand() % 4;
        sleep($a);
        return view('train.admin1');
    }

    public function admin(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('train.admin');
        }

        $input = $request->all();
        $uname = $input['username'];
        $password = $input['password'];
        $uname = strtolower($uname);
        $password = strtolower($password);
        try {
            sleep(2);
            $results = DB::connection('mysql2')->select("select * from users where `name`='" . $uname . "' and `password`='" . $password . "'");
        } catch (Exception $e) {
            echo "error";
            die;
        }
        if (count($results) == 0) {
            echo "账号或密码错误";
        } else {
            echo "恭喜你,这题的答案是 c3p0";
        }
        return view('train.admin');
    }

///////////////////////////////////////////////////////////
    public function download(Request $request, $file)
    {
        if ($file == 'hugefile') {
            $str = $request->headers->get('Range');
            if ($str == null || strpos($str, 'bytes') === false) {
                echo '这个文件100G,亲你真想下从头开始下完它么= =!';
            } else {
                echo '这题的答案是 content-range';
            }
        } else
            return response()->download("uploads/" . $file);
    }

    public function link(Request $request)
    {
        if ($request->isMethod('post')) {
			if(!Auth::check())return;
			if(Auth::user()->id!=19)return;
            $input = $request->all();
            Link::create($input);
        }
        $links = Link::all();
        foreach ($links as $link) {
            echo($link->first . " " . $link->second . "</br>");
        }

        return view("projects.link");
    }

    public function log(Request $request, $id)
    {
        Utils::log($request, 'log');
        $id = Utils::url2id($id);
        $user = User::find($id);
        if ($user == null) {
            return Redirect::to("404");
        }
        $solves = Solve::whereUseridAndType($user->id, 0)
            ->orderBy('id', 'asc')->get();
        $ns = array();
        foreach ($solves as $s) {
            $bb = false;
            foreach ($ns as $k => $v) {
                if ($ns[$k]->taskid == $s->taskid) {
                    $ns[$k]->rscore = max($ns[$k]->rscore, $s->rscore);
                    $bb = true;
                }
            }
            if (!$bb) {
                if ($s->taskid == 44) $s->rscore = $s->score * 100;
                if ($s->taskid == 80) $s->rscore = (1 + $s->score) * $s->score / 4 * 100;
                $ns[] = $s;
            }
        }
        foreach ($ns as $k => $s) {
            $task = Task::find($s->taskid);
            $ns[$k]['task'] = $task;

        }
        $type = 'log';
        return View::make('projects.guibu')->with(compact('ns'))->with(compact('user'))->with(compact('type'));
    }

}
